//
// Created by edward on 23-5-26.
//
#include <stdio.h>
#include <pb_encode.h>
#include <pb_decode.h>
#include "message.pb.h"

int main() {
    /* This is the buffer where we will store our message. */
    uint8_t buffer[BUFSIZ];
    size_t message_length;
    bool status;

    /* Encode our message */
    {
        /* Allocate space on the stack to store the message data.
         *
         * Nanopb generates simple struct definitions for all the messages.
         * - check out the contents of simple.pb.h!
         * It is a good idea to always initialize your structures
         * so that you do not have garbage data from RAM in there.
         */
        Message message = Message_init_zero;

        /* Create a stream that will write to our buffer. */
        pb_ostream_t stream = pb_ostream_from_buffer(buffer, BUFSIZ);

        /* Fill in the message */
        message.sender_id = 0;
        message.receiver_id = 1;
        message.command_id = 3;
        message.command_data = 0;
        message.has_info = true;
        message.info.obj_id = 1;
        message.info.master_id = 1;
        message.info.slave_id = 2;
        message.info.start_time = 123456789123456;
        message.info.end_time = 234567891234567;

        /* Now we are ready to encode the message! */
        status = pb_encode(&stream, Message_fields, &message);
        message_length = stream.bytes_written;

        /* Then just check for any errors... */
        if (!status)
        {
            printf("Encoding failed: %s\n", PB_GET_ERROR(&stream));
            return 1;
        }
    }

    /* Now we could transmit the message over network, store it in a file or
     * wrap it to a pigeon's leg.
     */

    /* But because we are lazy, we will just decode it immediately. */

    {
        /* Allocate space for the decoded message. */
        Message message = Message_init_zero;

        /* Create a stream that reads from the buffer. */
        pb_istream_t stream = pb_istream_from_buffer(buffer, message_length);

        /* Now we are ready to decode the message. */
        status = pb_decode(&stream, Message_fields, &message);

        /* Check for errors... */
        if (!status)
        {
            printf("Decoding failed: %s\n", PB_GET_ERROR(&stream));
            return 1;
        }

        /* Print the data contained in the message. */
        printf("sender_id: %d\n", message.sender_id);
        printf("receiver_id: %d\n", message.receiver_id);
        printf("command_id: %d\n", message.command_id);
        printf("command_data: %d\n", message.command_data);
        if (message.has_info) {
            printf("info.obj_id: %d\n", message.info.obj_id);
            printf("info.master_id: %d\n", message.info.master_id);
            printf("info.slave_id: %d\n", message.info.slave_id);
            printf("info.start_time: %lld\n", message.info.start_time);
            printf("info.end_time: %lld\n", message.info.end_time);
        }
    }

    return 0;

}